package com.ruoyi.imports.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.ruoyi.imports.domain.RawWaterExcelData;

import java.util.ArrayList;
import java.util.List;

public class RawWaterExcelListener implements ReadListener<RawWaterExcelData> {
    // 前3行是标题（索引0、1、2），从第4行（索引3）开始是数据
    private static final int HEADER_ROW_COUNT = 3;
    private static final int BATCH_COUNT = 500;
    private List<RawWaterExcelData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final List<RawWaterExcelData> dataList = new ArrayList<>();
    // 行索引从0开始
    private int currentRowIndex = 0;

    @Override
    public void invoke(RawWaterExcelData data, AnalysisContext context) {
        currentRowIndex = context.readRowHolder().getRowIndex(); // 获取正确的行索引（从0开始）

        // 跳过前3行标题（索引0、1、2）
        if (currentRowIndex < HEADER_ROW_COUNT) {
            return;
        }

        // 检查关键字段是否为空
        if (data.getDate() == null || data.getTime() == null) {
            System.out.println("忽略无效数据（日期/时间为空），第 " + (currentRowIndex + 1) + " 行：" + data);
            return;
        }

        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            // 处理批量数据（可选）
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

        System.out.println("日期：" + data.getDate() + "，时间：" + data.getTime());
        dataList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("Excel 数据读取完成，共 " + dataList.size() + " 行");
    }

    public List<RawWaterExcelData> getDataList() {
        return dataList;
    }
}